#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include "SDL/SDL_ttf.h"
#include <string>
#include "game.h"
#include "gameengine.h"

GameEngine* eg = NULL;
Sprite* plane = NULL;
std::vector<Sprite*> bullets;

bool SDLInit()
{
    //Initialize all SDL subsystems
    if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
    {
        return false;
    }

    //Initialize SDL_ttf
    if( TTF_Init() == -1 )
    {
        return false;
    }

    //If everything initialized fine
    return true;
}

void SDLClean()
{
    //Quit SDL_ttf
    TTF_Quit();

    //Quit SDL
    SDL_Quit();
}

bool GameInit()
{
    eg = GameEngine::GetInstance();

    if (eg == NULL)
        return false;

    if (eg->Initialize(320, 240, 32, "texun", 30) == false)
        return false;

    return true;
}

void GameStart()
{
    srand(SDL_GetTicks());

    SDL_Rect bound;
    bound.x = bound.y = 0;
    bound.w = 320;
    bound.h = 240;

    plane = new Sprite("plane.png");
    plane->SetPosition(eg->GetWidth() / 2, eg->GetHeight() / 2);
    plane->SetVelocity(0, 0);
    plane->SetBound(bound);
    eg->AddSprite(plane);

    Sprite* bul;
    for (int i=0; i<20; ++i)
    {
        bul = new Sprite("bullet.png", BA_WRAP);
        bul->SetPosition(rand() % eg->GetWidth(), rand() % eg->GetHeight());
        bul->SetVelocity(rand() % 5 - 2, rand() % 5 - 2);
        bul->SetBound(bound);
        bullets.push_back(bul);
        eg->AddSprite(bul);
    }
}

bool GameClean()
{
}

void GamePaint()
{
    eg->DrawSprite();
    eg->UpdateSurface();
}

void GameCycle()
{
    eg->UpdateSprite();

    if (eg->CheckSpriteCollision(plane))
        eg->SetSleep(true);

    GamePaint();
}

void HandleEvent(SDL_Event event)
{
    Point oldVel = plane->GetVelocity();
    //If a key was pressed
    if( event.type == SDL_KEYDOWN )
    {
        //Adjust the velocity
        switch( event.key.keysym.sym )
        {
            case SDLK_UP: plane->SetVelocity(oldVel.x, oldVel.y - 3); break;
            case SDLK_DOWN: plane->SetVelocity(oldVel.x, oldVel.y + 3); break;
            case SDLK_LEFT: plane->SetVelocity(oldVel.x - 3, oldVel.y); break;
            case SDLK_RIGHT: plane->SetVelocity(oldVel.x + 3, oldVel.y); break;
        }
    }
    //If a key was released
    else if( event.type == SDL_KEYUP )
    {
        //Adjust the velocity
        switch( event.key.keysym.sym )
        {
            case SDLK_UP: plane->SetVelocity(oldVel.x, oldVel.y + 3); break;
            case SDLK_DOWN: plane->SetVelocity(oldVel.x, oldVel.y - 3); break;
            case SDLK_LEFT: plane->SetVelocity(oldVel.x + 3, oldVel.y); break;
            case SDLK_RIGHT: plane->SetVelocity(oldVel.x - 3, oldVel.y); break;
        }
    }
}

bool SpriteCollision(Sprite* spriteHitter, Sprite* spriteHittee)
{
    return true;
}
